# import os
# from string import Template
# from playwright.async_api import async_playwright
# from mcp.server.fastmcp import FastMCP
from fastmcp import FastMCP
mcp = FastMCP("SearchLyricService")

apiUrl = "https://api.top237.top/ry-api"

# 使用示例
@mcp.tool()
def get_lyric(keyword: str) -> str:
    """根据关键词搜索歌词,展示搜索结果，不做其他处理。
    Args:
        keyword: 关键词
    Returns:
        str: 搜索结果
    """
    import urllib.request
    import urllib.parse
    import json 
    # 对关键词进行URL编码
    encoded_keyword = urllib.parse.quote(keyword)
    url = f"{apiUrl}/start/zanmei/searchByLryic?keyword={encoded_keyword}"
    with urllib.request.urlopen(url) as response:
        data = json.loads(response.read().decode())
        if data["code"] == 200:
            list = data["data"]
            titles = ""
            for item in list: 
                titles += item["title"] + "\n"
                titles += "id:" + item["id"] + "\n"
                titles += "所属诗集：" + item["shijiname"] + "\n"
                titles += "歌词：" + item["dmturl"]["lyric"] + "\n"
            return titles
        else:
            return "没有查询到数据"


@mcp.tool()
def get_detail(id: str) -> str:
    """根据id获取歌曲的详情
    Args:
        id: 歌词id
    Returns:
        str: 歌曲详情
    """
    import urllib.request
    import json 
    url = f"{apiUrl}/start/zanmei/sgb/{id}"
    with urllib.request.urlopen(url) as response:
        data = json.loads(response.read().decode())
        if data["code"] == 200:
            detail = data["data"]
            dmt = detail["dmturl"]
            titles = ""
            titles += detail["title"] + "\n"
            titles += "所属诗集：" + detail["shijiname"] + "\n"
            titles += "歌词：" + dmt["lyric"] + "\n"
            titles += "音频播放地址：" + dmt["adUrl"] + "\n"
            titles += "歌谱：" + dmt["gepuUrl"] + "\n"
            if dmt["pptUrl"]:
                titles += "PPT：" + dmt["pptUrl"] + "\n"
            if dmt["lrc"]:
                titles += "LRC歌词：" + dmt["lrc"] + "\n"
            return titles
        else:
            return "没有查询到数据"
if __name__ == "__main__":
    
    # 搜索歌词
    # lyric = get_detail("5b00f970605d87b30340f35540469ebf")
    # print(lyric) 
   

    # 以HTTP服务方式运行
    mcp.run(transport="http", host="localhost", port=8004)

    # 以STDIO服务方式运行
    # mcp.run(transport="stdio")


 